const path = require('path')
const favicon = require('serve-favicon')
const compress = require('compression')
const cors = require('cors')
const helmet = require('helmet')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')

const feathers = require('feathers')
const configuration = require('feathers-configuration')
const hooks = require('feathers-hooks')
const rest = require('feathers-rest')
const socketio = require('feathers-socketio')

const app = feathers()
// Load app configuration
app.configure(configuration(path.join(__dirname, '..')))
// Enable CORS, security, compression, favicon and body parsing
let whitelist = [
  'http://localhost:4200',
]
let corsOptions = {
  origin: function (origin: string, callback: Function) {
    if (
      !origin || 
      origin.startsWith('http://localhost') || 
      whitelist.indexOf(origin) !== -1
    ) {
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))
    }
  },
  credentials: true,
}
app.use(cors(corsOptions))
app.use(helmet())
app.use(compress())
app.use(cookieParser())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(favicon(path.join(app.get('public'), 'favicon.ico')))
app.use('/', feathers.static(app.get('public')))

app.configure(hooks())
app.configure(rest())
app.configure(socketio(require('./socket/index')))

app.use(function(req: any, res: any, next: Function) {
  //踢出登录
  // req.cookies = {}
  next()
})
app.configure(require('./authentication'))
app.configure(require('./services'))
app.configure(require('./database'))
app.configure(require('./middleware'))
app.hooks(require('./app.hooks'))

export = app
